<?php
namespace app\backstage\controller;
use app\backstage\classes\helper\XlsTools;
use app\common\classes\ReportOrder;
use think\Controller;
use think\Db;
use think\facade\Request;

class Order extends Controller
{
    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => []],
    ];

    public function index()
    {
        $role = request()->_role;
        $qas = \app\common\model\QuickApp::getList();
        $this->assign('qas', $qas);
        $this->assign('role_name', request()->_role->alias);
        $this->assign('channels', sonUsers('channel'));
        $this->assign('agents', sonUsers('agent'));
        $this->assign('role', request()->_role);
        return $this->fetch();
    }

    public function list_data()
    {
        $params = Request::param('', '', 'strip_tags,trim');
        $Order = \think\facade\App::model('Order', 'logic');
        $result = $Order->getList($params);

        if ($result['count'] > 0) {

            return ['code' => 0, 'msg' => '数据获取成功', 'count' => $result['count'], 'data' => $result['list'],'totalRow'=>$result['totalRow']];
        }

        return ['code' => 1, 'msg' => '暂无数据', 'count' => $result['count'], 'data' => $result['list'], 'totalRow' => $result['totalRow']];
    }

    /*订单导出*/
    public function export()
    {
        ini_set ('memory_limit', "-1") ;
        $params = Request::param('', '', 'strip_tags');
        $params['page'] = 1;
        $params['limit'] = 1000000;
        $Order = \think\facade\App::model('Order', 'logic');
        $result = $Order->getList($params);

        $xlsTools = new XlsTools();
        $xlsTools->start([
            'title'=>[  '订单ID','订单号','用户ID','类型','代理','投放号','App','手机型号','充值金额','充值详情','充值次数',
                '订单来源','支付状态','激活时间','下单时间','支付时间','下单IP','广告来源','广告账户信息','计划ID','组ID','创意ID'],   //列名
            'type'=>'xls',               //导出的excel的类型
            'name'=>'订单明细'                //导出的excel的文件名
        ]);

        foreach ($result['list'] as $v)
        {
            $row = [ 0 => $v['id'] ,1 => $v['out_trade_no'] , 2 => $v['uid'] , 3 => $v['recharge_type_format'] ,
                4 => $v['agent_name'], 5 => $v['channel_name'],6 => $v['quick_name'],
                7 => $v['phone_model'], 8 => $v['total_fee'], 9 => $v['recharge_info'], 10 => $v['recharge_times'],
                11 => $v['source'],12 => $v['state'],13 => $v['create_time_user'],14 => $v['create_time'],
                15 => $v['pay_time'],16=>$v['ip_addr'],17=>$v['media_name'],18=>$v['advertiser_id'],19=>$v['aid'],
                20 => $v['campaign_id'],21=>$v['cid']
            ];
            $xlsTools->oneData($row);
        }

        /*结束导出*/
        $xlsTools->end();
    }

    /*手动上报订单*/
    public function report()
    {
        $params = Request::param('', '', 'strip_tags');

        $orderInfo = Db::table('pay_order')->where('id',$params['id'])
            ->field('id,is_report,quick_id,uid,total_fee,channel_id,create_time,link_id,recharge_type,recharge_times,advert_media_id,nid,update_time,create_time')
            ->findOrEmpty();

        if(empty($orderInfo))
        {
            return json(['code'=>101,'msg'=>'订单记录不存在']);
        }

        if($orderInfo['is_report'] == 2){
            return json(['code'=>101,'msg'=>'订单已上报，请勿重复上报']);
        }

        $stop_time = strtotime('2024-06-03 00:00:00');
        /*if($orderInfo['advert_media_id'] == 1 && time() >= $stop_time)
        {
            return json(['code'=>101,'msg'=>'快手端口回传关闭']);
        }*/


        $field = "advert_media_id,report_ab,report_jb,report_rb,report_ao,report_old_fans,report_caliber,report_full";
        $field .= ",report_order_bn,misreporting_type,misreporting_percentage,misreporting_loop_proportion,status";

        $recordLink = Db::table('quick_backhaul_link')->where('link_id',$orderInfo['link_id'])
            ->where('channel_id',$orderInfo['channel_id'])
            ->field($field)
            ->findOrEmpty();

        if(empty($recordLink))
        {
            return json(['code'=>101,'msg'=>'推广链接未设置媒体回传']);
        }

        $recordAdvert = Db::table('pay_order_advert')->where('order_id',$orderInfo['id'])
            ->field('order_id,behavior_id')->find();

        if(empty($recordAdvert))
        {
            return json(['code'=>101,'msg'=>'无匹配广告行为']);
        }

        $ReportOrder = new ReportOrder();
        $result = $ReportOrder->report_hand($orderInfo,$recordAdvert['behavior_id']);

        return json($result);
    }

    /**
     * 退款动作
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function refund()
    {
        $params = Request::param('', '', 'strip_tags');
        $order = Db::table('pay_order')->where('id', $params['id'])->find();
        Db::table('pay_order_success')->where('out_trade_no', $order['out_trade_no'])->update(['is_refund' => 1]);
        $r = Db::table('pay_order')->where('id', $params['id'])->update(['is_refund' => 1]);
        if ($r !== false) {
            return json(['code' => 100, 'msg' => '退款成功']);
        }
        return json(['code' => 101, 'msg' => '退款异常，请联系管理员']);
    }

}